<template>
    <div class="app-container">

        <div class="filter-container" style="display: flex; align-items: flex-start;">

            <el-date-picker
                    v-model="listQuery.searchStatTimeStart"
                    type="date"
                    placeholder="开始日期"
                    format="yyyy-MM-dd"
                    :picker-options="pickerStartOption">
            </el-date-picker>

            <el-date-picker
                    v-model="listQuery.searchStatTimeEnd"
                    type="date"
                    placeholder="结束日期"
                    :picker-options="pickerEndOption">
            </el-date-picker>

            <el-select clearable style="width: 150px" class="filter-item" v-model="listQuery.searchResource" placeholder="选择来源渠道" @change="handleFilter">
                <el-option v-for="item in resourceOptions" :key="item" :label="item.name" :value="item.key">
                </el-option>
            </el-select>

            <el-select clearable style="width: 150px;margin-left: 20px;" class="filter-item" v-model="listQuery.orderKey" placeholder="排序方式" @change="handleFilter">
                <el-option v-for="item in orderKeyOptions" :key="item.key" :label="item.name" :value="item.key">
                </el-option>
            </el-select>

            <el-button class="filter-item" style="margin-left: 20px;" type="primary" icon="search" @click="handleFilter">搜索</el-button>
            <el-button class="filter-item" type="warning" icon="delete2" @click="resetQuery">重置</el-button>
            <el-button class='filter-item' style="margin-left: 20px;" type="primary" icon="document" @click="handleDownload">导出excel</el-button>
        </div>

        <div class="filter-container">
            <el-radio-group v-model="searchType" @change="getList">
                <el-radio-button label="day">按天</el-radio-button>
                <el-radio-button label="month">按月</el-radio-button>
            </el-radio-group>
        </div>

        <el-table :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit highlight-current-row>

            <el-table-column label='日期' align="center" width="150">
                <template scope="scope">
                    <span v-if="searchType==='day'">
                        {{scope.row.statDate|parseDate('day')}}
                    </span>
                    <span v-if="searchType==='month'">
                        {{scope.row.statDate|parseDate('month')}}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="来源渠道" align="center" width="150">
                <template scope="scope">
                    {{scope.row.channel|parseChannel}}
                </template>
            </el-table-column>
            <el-table-column label="百度统计UV" align="center" width="150">
                <template scope="scope">
                    {{scope.row.uvCount ? scope.row.uvCount : 0}}
                </template>
            </el-table-column>
            <el-table-column label="百度统计PV" align="center" width="150">
                <template scope="scope">
                    {{scope.row.pvCount ? scope.row.pvCount : 0}}
                </template>
            </el-table-column>
            <el-table-column label="注册用户数" align="center" width="150">
                <template scope="scope">
                    {{scope.row.newUsers}}
                </template>
            </el-table-column>
            <el-table-column label="总订单数" align="center">
                <template scope="scope">
                    {{scope.row.totalOrders}}
                </template>
            </el-table-column>
            <el-table-column label="总金额" align="center">
                <template scope="scope">
                    ￥{{scope.row.totalAmount|priceFormat}}元
                </template>
            </el-table-column>
            <el-table-column label="总成交订单数" align="center">
                <template scope="scope">
                    {{scope.row.dealOrders}}
                </template>
            </el-table-column>
            <el-table-column label="总成交金额" align="center">
                <template scope="scope">
                    ￥{{scope.row.dealAmount|priceFormat}}元
                </template>
            </el-table-column>
        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
                           :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
    import { getStatisticsByDay, getStatisticsByMonth } from '@/api/statorder';
    import { getOrderKey } from '@/api/common';
    import { priceFormat, parseTime, parseDate } from '@/filters/index';

    var defaultListQuery = {
        page: 1,
        pageSize: 30,
        searchResource: 'ALL',
        orderKey: 'STAT_DATE_DESC',
        searchStatTimeStart: '',
        searchStatTimeEnd: ''
    }

    export default {
        data() {
            var listQuery = JSON.parse(JSON.stringify(defaultListQuery));
            var listQueryJson = sessionStorage.getItem(this.$route.path.replace(/\//g, '_'));
            if (listQueryJson) {
                listQuery = JSON.parse(listQueryJson);
            }
            return {
                list: null,
                total: null,
                resourceOptions: [
                    { name: '全部渠道', key: 'ALL' },
                    { name: '泰迪熊', key: 'TED' },
                    { name: '微信', key: 'WX' },
                    { name: '其他', key: 'OTHER' }
                ],
                searchType: 'day',
                orderKeyOptions: [
                ],
                listQuery: listQuery,
                listLoading: true,
                pickerStartOption: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                pickerEndOption: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                selectedRowID: sessionStorage.getItem(this.$route.path.replace(/\//g, '_') + '_selected_row_id')
            }
        },
        created() {
            this.getList();
            this.getOrderKeyList();
        },
        methods: {
            resetQuery() {
                this.listQuery = JSON.parse(JSON.stringify(defaultListQuery));
                this.selectedRowID = '';
                sessionStorage.removeItem(this.$route.path.replace(/\//g, '_') + '_selected_row_id')
                this.getList();
            },
            tableRowClassName(row) {
                if (this.selectedRowID && row.id == this.selectedRowID) {
                    return 'sstt-selected-row';
                }
            },
            getList() {
                this.listLoading = true;
                let _getList = getStatisticsByDay;
                if (this.searchType === 'day') {
                    _getList = getStatisticsByDay;
                } else {
                    _getList = getStatisticsByMonth;
                }
                if (typeof this.listQuery.searchStatTimeStart == 'object') {
                    this.listQuery.searchStatTimeStart = parseTime(this.listQuery.searchStatTimeStart, '{y}-{m}-{d} 00:00:00');
                }
                if (typeof this.listQuery.searchStatTimeEnd == 'object') {
                    this.listQuery.searchStatTimeEnd = parseTime(this.listQuery.searchStatTimeEnd, '{y}-{m}-{d} 23:59:59');
                }
                _getList(this.listQuery).then(response => {
                    this.list = response.data.data;
                    this.total = response.data.totalCount;
                    this.listLoading = false;
                    sessionStorage.setItem(this.$route.path.replace(/\//g, '_'), JSON.stringify(this.listQuery));
                }).catch(err => {
                    console.log(err)
                    this.listLoading = false;
                });
            },
            getOrderKeyList() {
                getOrderKey('admin_statistics').then(response => {
                    this.orderKeyOptions = this.orderKeyOptions.concat(response.data);
                }).catch(err => {
                    console.log(err)
                });
            },
            handleFilter() {
                this.getList();
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.page = val;
                this.getList();
            },
            handleDownload() {
                const copyQuery = JSON.parse(JSON.stringify(this.listQuery));
                copyQuery.page = 1;
                copyQuery.pageSize = 1000;
                if (typeof this.listQuery.searchStatTimeStart == 'object') {
                    copyQuery.searchStatTimeStart = parseTime(this.listQuery.searchStatTimeStart, '{y}-{m}-{d} 00:00:00');
                }
                if (typeof this.listQuery.searchStatTimeEnd == 'object') {
                    copyQuery.searchStatTimeEnd = parseTime(this.listQuery.searchStatTimeEnd, '{y}-{m}-{d} 23:59:59');
                }

                let _getList = getStatisticsByDay;
                let fileName = '统计增长';
                if (this.searchType === 'day') {
                    fileName = '按天统计增长';
                    _getList = getStatisticsByDay;
                } else {
                    fileName = '按月统计增长';
                    _getList = getStatisticsByMonth;
                }
                _getList(copyQuery).then(response => {
                    const dataList = response.data.data;
                    require.ensure([], () => {
                        const { export_json_to_excel } = require('@/vendor/Export2Excel');
                        dataList.forEach(item => {
                            item.totalAmount = priceFormat(item.totalAmount);
                            item.dealAmount = priceFormat(item.dealAmount);
                            item.statDate = parseDate(item.statDate, this.searchType);
                        });
                        const tHeader = ['日期', '注册用户数', '总订单数', '总金额(元)', '总成交订单数', '总金额(元)'];
                        const filterVal = ['statDate', 'newUsers', 'totalOrders', 'totalAmount', 'dealOrders', 'dealAmount'];
                        const data = this.formatJson(filterVal, dataList);
                        export_json_to_excel(tHeader, data, fileName);
                    })
                }).catch(err => {
                    console.log(err)
                });
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => v[j]))
            }
        }
    };
</script>